<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class AdminConfig extends Model {
    use HasDateTimeFormatter;
    protected $table = 'admin_config';
    static $input_type = [
        'input' => "文本输入框",
        'number' => "数字输入",
        'radio' => "单选",
        'checkbox' => "多选",
        'textarea' => '文本框',
        'editor' => "富文本",
        'select' => "下拉选择",
        'image' => '图片',
    ];
    /**
     * 从数据区获取配置并缓存
     * @param  string $key            [description]
     * @return [type]                 [description]
     */
    static function loadConfig($key = "") {
        $obj = self::where("name", $key)->first();
        Cache::put($key, $obj);
        return $obj;
    }

    /**
     * 获取单个配置项, 默认先从缓存读取, 再从服务器中读取
     * @Author MrGuo
     * @Date   2020-08-07
     * @param  string      $key [键名]
     * @param  int|integer $obj [是否返回对象, 默认否, 大于0是]
     * @return [type]           [description]
     */
    static function getConfig(string $key = "", int $obj = 0) {
        if (!Cache::has($key)) {
            self::loadConfig($key);
        }
        $config = Cache::get($key);

        if (intval($obj) > 0 || $config == null) {
            return $config;
        }
        switch ($config['type']) {
            default:
                return $config['value'];
                break;
        }
    }
    /**
     * 获取字段类型 , 不传值默认返回数组
     * @Author MrGuo
     * @param  string|null $type           [description]
     * @return [type]                      [description]
     */
    static function getInputType(string $type = null) {
        if (!empty($type)) {
            if (isset(self::$input_type[$type])) {
                return self::$input_type[$type];
            } else {
                return '';
            }
        }
        return self::$input_type;
    }
    /**
     * 获取字段分组, 不传获取所有
     * @Author MrGuo
     * @param  string|null $type          [description]
     * @return [type]                      [description]
     */
    static function getConfigGroup(string $group = null) {
        $group = [];
        $obj = self::getConfig('config_group', 1);
        if (empty($obj)) {
            return $group;
        }

        $arr = explode(",", str_ireplace("\r\n", ",", $obj->options));
        if (gettype($arr) == 'string') {
            $arr = [$arr];
        }

        foreach ($arr as $key => $val) {
            $arr2 = explode(":", $val);
            if (gettype($arr2) == "array" && count($arr2) > 1) {
                $group[$arr2[0]] = $arr2[1];
            }
        }

        return $group;
    }

}
